/* 
 * File:   lm335.c
 * Author: bryan
 *
 * Created on 5 de septiembre de 2014, 22:26
 */

# include <p18f2550.h>
# include <plib/xlcd.h>
# include <plib/delays.h>
// retardo del la lcd
void DelayFor18TCY(void){Delay10TCYx(2);};
void DelayPORXLCD(void){Delay1KTCYx(5);};
void DelayXLCD(void){Delay10KTCYx(2);};
void main(){
    TRISB=0;
    TRISC=0;
    ADCON1=13;
    ADCON2=12;
    TXSTA=36;
    SPBRG=25;
    RCSTA=128;
    BAUDCON=0;
    OpenXLCD( FOUR_BIT & LINES_5X7 );//configuracion de la lcd
    WriteCmdXLCD(1);//borra la lcd
    SetDDRamAddr(0x05);
    putrsXLCD("Temperatura");
    int t1,h,aux,aux2,aux3;
    while(1){
//      Combercion de manera completa sin perdida de datos
        ADCON0=3;
        while(ADCON0==3){}
        aux3=(ADRESL>>6)|(ADRESH<<2);
        aux2=aux3*4.882/10;
        t1=aux2-272;

        if(t1<0 && t1!=aux){
            aux=t1;
            t1=t1*(-1);
            h=1;
            SetDDRamAddr(0x42);//asigna posicion de escritura
            putrsXLCD(" - ");// Si el numero es negativo escribe -
            WriteDataXLCD(0x30+(t1/100));//discrimina las centenas
            WriteDataXLCD(0x30+(t1/10));//discrimina las decenas
            WriteDataXLCD(0x30+(t1%10));//descrimina las unidades
        }
        else if(t1!=aux){
            aux=t1;
            h=0;
            SetDDRamAddr(0x42);//asigna posicion de escritura
            putrsXLCD("   ");//borra las tres primeras pociciones
            WriteDataXLCD(0x30+(t1/100));//discrimina las centenas
            WriteDataXLCD(0x30+(t1/10));//discrimina las decenas
            WriteDataXLCD(0x30+(t1%10));//descrimina las unidades
        }
        //CONFIGURA LA ALARMA
        if(t1>90){PORTC=15;Delay10KTCYx(50);PORTC=0;Delay10KTCYx(40);}else{PORTC=0;}
        if(aux!=t1){
//          discriminacion del sensor
            TXREG=' ';
            while(!TXSTA1bits.TRMT){}
            TXREG='S';
            while(!TXSTA1bits.TRMT){}
            TXREG='1';
            while(!TXSTA1bits.TRMT){}
            TXREG='=';
            while(!TXSTA1bits.TRMT){}
            if(h==1){
                TXREG=' ';
                while(!TXSTA1bits.TRMT){}
                TXREG='-';
                while(!TXSTA1bits.TRMT){}
                TXREG=' ';
                while(!TXSTA1bits.TRMT){}
            }
//          Envio de datos numericos
            TXREG=(t1/100)+0x30;
            while(!TXSTA1bits.TRMT){}
            TXREG=(t1/10)+0x30;
            while(!TXSTA1bits.TRMT){}
            TXREG=(t1%10)+0x30;
            while(!TXSTA1bits.TRMT){}
            aux=t1;
//          Equivalente a un tap
            TXREG=0x0d;
            while(!TXSTA1bits.TRMT){}
            Delay10KTCYx(20);
        }
    }
}
